package com.sj.mbt.ui.machine;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.sj.friendcircle.common.router.RouterList;
import com.sj.mbt.R;
import com.sj.mbt.ui.adapter.MachinePagerAdapter;
import com.sj.mbt.ui.machine.fragment.MachineFragment;
import com.sj.mbt.widget.coordinatortablayout.CoordinatorTabLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.rongcloud.im.App;
import cn.rongcloud.im.server.network.http.HttpException;
import cn.rongcloud.im.server.response.CoinCountByUserResponse;
import cn.rongcloud.im.server.response.MachineUserListResponse;
import cn.rongcloud.im.server.response.UserInfoResponse;
import cn.rongcloud.im.server.utils.NToast;
import cn.rongcloud.im.server.widget.SelectableRoundedImageView;
import cn.rongcloud.im.ui.activity.base.BaseAppCompatActivity;
import io.rong.imageloader.core.ImageLoader;

/**
 * 矿机
 */
@Route(path = RouterList.MachineListActivity.path)
public class MachineListNewActivity extends BaseAppCompatActivity implements MachineFragment.OnFragmentInteractionListener {

    private static final int MACHINE_USER_BY_PAGE = 1;
    private static final int GET_USER = 2;
    private static final int COIN_COUNT_BY_USER = 3;
    private static final int COIN_LIST = 4;
    private static final int MACHINE_OPEN = 5;
    private static final int MACHINE_CLOSE = 6;

    @BindView(R.id.view_pager)
    ViewPager mViewPager;
    @BindView(R.id.coordinatortablayout)
    CoordinatorTabLayout mCoordinatorTabLayout;

    SelectableRoundedImageView myHeader;
    TextView tvName;
    TextView tvCoin;
    TextView tvMachineUserLevel;
    LinearLayout llAddMachine;

    private int pageNum = 1;
    private int pageSize = 20;
    private String coinid = "1";//脉宝币
    private String machineId;
    private ArrayList<MachineFragment> mFragments;
    private final String[] mTitles = {"迷你", "初级", "中级", "高级"};
    private MachinePagerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_machine_new_list);
        ButterKnife.bind(this);
        setHeadVisibility(ViewPager.GONE);

        initFragments();
        initViewPager();

        View view = LayoutInflater.from(this).inflate(R.layout.include_machine_new_header, null);

        initHeaderView(view);


        request(GET_USER);
        request(COIN_COUNT_BY_USER);
        request(MACHINE_USER_BY_PAGE);
//        request(COIN_LIST);
        mCoordinatorTabLayout.setTranslucentStatusBar(this)
                .setTitle("挖机")
                .setmLlHeaderView(view)
                .setBackEnable(true)
                .setupWithViewPager(mViewPager);
    }

    private void initHeaderView(View view) {
        myHeader = view.findViewById(R.id.my_header);
        tvName = view.findViewById(R.id.tv_name);
        tvCoin = view.findViewById(R.id.tv_coin);
        tvMachineUserLevel = view.findViewById(R.id.tv_machine_user_level);
        llAddMachine = view.findViewById(R.id.ll_add_machine);
    }

    private void initFragments() {
        mFragments = new ArrayList<>();
        for (String title : mTitles) {
            mFragments.add(MachineFragment.getInstance(title));
        }
    }

    private void initViewPager() {
        mViewPager.setOffscreenPageLimit(4);
        adapter = new MachinePagerAdapter(getSupportFragmentManager(), mFragments, mTitles);
        mViewPager.setAdapter(adapter);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public Object doInBackground(int requestCode, String id) throws HttpException {
        switch (requestCode) {
            case MACHINE_USER_BY_PAGE:
                return action.listMachineUserByPage(pageNum + "", pageSize + "");
            case GET_USER:
                return action.getUser();
            case COIN_COUNT_BY_USER:
                return action.getCoinCountByUser(coinid);
            case COIN_LIST:
                return action.coinList();
            case MACHINE_OPEN:
                return action.machineOpen(machineId);
            case MACHINE_CLOSE:
                return action.machineClose(machineId);
        }
        return super.doInBackground(requestCode, id);
    }

    @Override
    public void onSuccess(int requestCode, Object result) {
        if (result != null) {
            switch (requestCode) {
                case MACHINE_USER_BY_PAGE:
                    MachineUserListResponse scrres = (MachineUserListResponse) result;
                    if (scrres.getResultCode() == 0) {
                        List<MachineUserListResponse.DataBean> data = scrres.getData();
                        machineCount(data);
                        if (adapter == null) return;
                        for (MachineFragment fragment : adapter.getmFragments()) {
                            fragment.setData(data);
                        }
                    } else {
                        NToast.shortToast(mContext, scrres.getMsg());
                    }
                    break;
                case COIN_COUNT_BY_USER:
                    CoinCountByUserResponse coinCountByUserResponse = (CoinCountByUserResponse) result;
                    if (coinCountByUserResponse.getResultCode() == 0) {
                        tvCoin.setText(coinCountByUserResponse.getData());
                    } else {
                        NToast.shortToast(mContext, coinCountByUserResponse.getMsg());
                    }
                    break;
                case GET_USER:
                    UserInfoResponse userInfoResponse = (UserInfoResponse) result;
                    if (userInfoResponse.getResultCode() == 0) {
                        String portraitUri = userInfoResponse.getData().getHeadimage();
                        ImageLoader.getInstance().displayImage(portraitUri, myHeader, App.getOptions());
                        tvName.setText(userInfoResponse.getData().getName());
                    } else {
                        NToast.shortToast(mContext, userInfoResponse.getMsg());
                    }
                    break;
            }
        }
    }

    @Override
    public void onFailure(int requestCode, int state, Object result) {
        switch (requestCode) {
            default:
                NToast.shortToast(mContext, "请求失败！");
                break;
        }
    }

    @Override
    public void onFragmentInteraction(Uri uri) {
        request(MACHINE_USER_BY_PAGE);
    }

    /**
     * 矿机数量
     *
     * @param data
     */
    private void machineCount(List<MachineUserListResponse.DataBean> data) {
        int machineA = 0, machineB = 0, machineC = 0, machineD = 0;
        for (MachineUserListResponse.DataBean dataBean : data) {
            if (dataBean.getLevel() == 5201) {
                machineA++;
            } else if (dataBean.getLevel() == 5202) {
                machineB++;
            } else if (dataBean.getLevel() == 5203) {
                machineC++;
            } else if (dataBean.getLevel() == 5204) {
                machineD++;
            }
        }
        tvMachineUserLevel.setText(String.format("A级(%d)B级(%d)C级(%d)D级(%d)",machineA,machineB,machineC,machineD));
    }
}
